﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Shop : MonoBehaviour
{
    public GameObject m_WeaponDescriptionPanel;
    public GameObject m_ShipDescriptionPanel;
    public GameObject m_MaterialDescriptionPanel;

    public GameObject m_WeaponShopPanel;
    public GameObject m_MaterialShopPanel;
    public GameObject m_ShipShopPanel;
    public GameObject m_WaterBoxShopPanel;

    public Text m_MoneyText;
    public GameObject m_CommodityItem;
    public GameObject m_CommodityShip;
    public GameObject m_SellItemItemPerfab;
    public GameObject m_SellShipItemPerfab;
    public Barrage m_BarragePerfab;
    public GameObject m_BarrageParent;

    public AudioSource m_WelcomZH;
    public AudioSource m_WelcomEN;
    public AudioSource m_WelcomJP;

    public AudioSource m_BuySound;
    public AudioSource m_SellSound;
    public WeaponFilterPanel m_WeaponFilterPanel;

    List<AudioSource> m_Welcoms = new List<AudioSource>();

    int m_Seed;
    int m_CommodityNumber = 0;

    List<CommodityItem> m_ItemList = new List<CommodityItem>();
    List<CommodityShip> m_ShipList = new List<CommodityShip>();
    List<GameObject> m_WaterBoxList = new List<GameObject>();

    List<SellItemItem> m_SellItem = new List<SellItemItem>();
    List<SellShipItem> m_SellShips = new List<SellShipItem>();

    private void Awake()
    {
        m_Welcoms.Add(m_WelcomZH);
        m_Welcoms.Add(m_WelcomEN);
        m_Welcoms.Add(m_WelcomJP);
    }

    void Start()
    {
        initShopList();
    }
    private void OnEnable()
    {
        m_Welcoms[UnityEngine.Random.Range(0, 3)].Play();
    }


    float m_CurrentBarrageSendTime = 3;
    float m_CurrentBarrageSendMaxTime = 3;
    float m_BarrageSendMaxTime = 3;
    void Update()
    {
        if(m_MoneyText != null)
        {
            m_MoneyText.text = Player.Instance.Money.ToString();
        }

        //  更新弹幕
        m_CurrentBarrageSendTime += Time.deltaTime;
        if (m_CurrentBarrageSendTime > m_CurrentBarrageSendMaxTime)
        {
            m_CurrentBarrageSendTime = 0;
            m_CurrentBarrageSendMaxTime = UnityEngine.Random.Range(0, m_BarrageSendMaxTime);
            var barrage = Instantiate(m_BarragePerfab);
            barrage.transform.SetParent(m_BarrageParent.transform);
        }
    }


    void initShopList()
    {
        //  初始化日期种子
        m_Seed = UtilsGame.GetSeedToday();
        m_CommodityNumber = (int)(((UtilsMath.rand(m_Seed, m_Seed + 1) + 1) / 2) * 15 + 7);
        if (Player.Instance.m_DevelopmentMode == true)
            m_CommodityNumber *= 10;

        //  新的一天卖新的东西
        if (Player.Instance.m_ShopUpdateDate < m_Seed)
        {
            Player.Instance.m_WeaponShopBuyIndices.Clear();
            Player.Instance.m_ShipShopBuyIndices.Clear();
            Player.Instance.m_ShopUpdateDate = m_Seed;
            Player.Instance.save();
        }


        //  初始化武器商店
        if (m_ItemList.Count == 0)
        {
            for (int i = 0; i < m_CommodityNumber; ++i)
            {
                Item.ItemsType itemId = (Item.ItemsType)(((UtilsMath.rand(m_Seed, i) + 1) / 2) * (int)((Item.ItemsType.WEAPON_END) - (Item.ItemsType.WEAPON_BEGIN + 1)) + (int)Item.ItemsType.WEAPON_BEGIN + 1);

                Item item = null;
                item = ItemFactory.Instance.createItem(Item.getItemEnumString(itemId));
                Weapon itemWeapon = item as Weapon; 
                if(itemWeapon == null || itemWeapon.ResearchInfluence == InfluenceMG.INFLUENCE_BLACKMARK)
                    continue;

                if (item == null)
                {
                    Debug.LogWarning("commodity id = " + (int)itemId);
                }
                if(itemWeapon != null)
                {
                    int numberMutiple = 1;
                    switch(itemWeapon.m_Level)
                    {
                        case Weapon.Level.LEVEL_BIG:
                            numberMutiple = 1;
                            break;
                        case Weapon.Level.LEVEL_MIDDLE:
                            numberMutiple = 3;
                            break;
                        case Weapon.Level.LEVEL_SMALL:
                            numberMutiple = 7;
                            break;
                    }
                    item.m_Number = Mathf.Max((int)(((UtilsMath.rand(m_Seed, m_CommodityNumber - i) + 1) / 2) * numberMutiple) , 1);
                }
                m_ItemList.Add(AddItemToPanel(m_WeaponShopPanel, item, i));
            }
        }
        foreach (var item in m_ItemList)
        {
            m_WeaponFilterPanel.CheckFilter(item);
            //  如果已经被购买了则藏起来
            for (int j = 0; j < Player.Instance.m_WeaponShopBuyIndices.Count; ++j)
            {
                if (Player.Instance.m_WeaponShopBuyIndices[j]%1000 == item.m_CommodityID)
                {
                    if (Player.Instance.m_WeaponShopBuyIndices[j] < 1000)
                        item.gameObject.SetActive(false);
                    else
                        item.Item.m_Number = Player.Instance.m_WeaponShopBuyIndices[j] / 1000;
                }
            }
        }

        //  初始化舰船商店
        if (m_ShipList.Count == 0)
        {
            m_CommodityNumber = (int)(((UtilsMath.rand(m_Seed, m_Seed + 1) + 1) / 2) * 5 + 3);
            if (Player.Instance.m_DevelopmentMode == true)
                m_CommodityNumber *= 100;
            List<GameObject> shipsPath = ShipManager.Instance.GetAllShipList();
            for (int i = 0; i < m_CommodityNumber; ++i)
            {
                int shipNumber = shipsPath.Count;
                int index = (int)(((UtilsMath.rand(m_Seed, i) + 1) / 2) * shipNumber);
                m_ShipList.Add(AddShipToPanel(m_ShipShopPanel, shipsPath[index], i));
            }
        }
        foreach (var shipUI in m_ShipList)
        {
            shipUI.gameObject.SetActive(true);
            //  如果已经被购买了则藏起来
            for (int j = 0; j < Player.Instance.m_ShipShopBuyIndices.Count; ++j)
            {
                if (Player.Instance.m_ShipShopBuyIndices[j] == shipUI.m_CommodityID)
                {
                    shipUI.gameObject.SetActive(false);
                }
            }
        }

        //   初始化秘密商店
        if (Commander.Instance.m_Member >= 1)
        {
            if (m_WaterBoxList.Count == 0)
            {
                var object2 = Resources.LoadAll("Perfabs/Ships/NetWorkFriend");
                for (int i = 0; i < object2.Length; ++i)
                {
                    var gobj = object2[i] as GameObject;
                    m_WaterBoxList.Add(AddShipToPanel(m_WaterBoxShopPanel, gobj).gameObject);
                }
                for(int i= (int)Item.ItemsType.NETFRIEND_WEAPON_BEGINE+1; i< (int)Item.ItemsType.NETFRIEND_WEAPON_END; ++i)
                {
                    var item = ItemFactory.Instance.createItem(((Item.ItemsType)i).ToString());
                    item.m_Number = 100;
                    m_WaterBoxList.Add(AddItemToPanel(m_WaterBoxShopPanel, item).gameObject);
                }
            }
            foreach (var shipUI in m_WaterBoxList)
            {
                shipUI.gameObject.SetActive(true);
            }
        }
    }

    public CommodityItem AddItemToPanel(GameObject panel, Item item, int id=0)
    {
        var itemObj = Instantiate(m_CommodityItem);
        CommodityItem itemUI = itemObj.GetComponent<CommodityItem>();
        itemUI.Item = item;
        itemUI.m_CommodityID = id;
        itemUI.OnBuy = OnItemBuyClicked;
        itemUI.m_DescriptionPanel = m_WeaponDescriptionPanel;
        itemUI.transform.SetParent(panel.transform);
        itemUI.transform.localScale = new Vector3(1, 1, 1);
        return itemUI;
    }
    public CommodityShip AddShipToPanel(GameObject panel, GameObject ship, int id = 0)
    {
        var shipObjUI = Instantiate(m_CommodityShip);
        CommodityShip shipUI = shipObjUI.GetComponent<CommodityShip>();
        GameObject shipObj = Instantiate(ship);
        if (shipObj)
        {
            shipObj.SetActive(false);
            shipUI.Ship = shipObj.GetComponent<Ship>();
            shipUI.m_DescriptionPanel = m_ShipDescriptionPanel;
            shipUI.m_CommodityID = id;
            shipUI.transform.SetParent(panel.transform);
            shipUI.transform.localScale = new Vector3(1, 1, 1);
        }
        return shipUI;
    }

    void InitSellShopList()
    {
        //  初始化道具
        var items = Player.Instance.Items;
        foreach(var item in items)
        {
            var sellItemUi = Instantiate(m_SellItemItemPerfab);
            if (!sellItemUi)
                continue;
            var sellItemCom = sellItemUi.GetComponent<SellItemItem>();
            if (sellItemCom)
            {
                sellItemCom.Item = item.Value;
                sellItemCom.OnSell = OnItemSellClicked;
                //sellItemCom.m_DescriptionPanel = m_WeaponDescriptionPanel;
            }

            if (ItemFactory.Instance.IsWeapon(item.Value.m_Type))
                sellItemUi.transform.SetParent(m_WeaponShopPanel.transform);
            else if(ItemFactory.Instance.IsMaterial(item.Value.m_Type))
                sellItemUi.transform.SetParent(m_MaterialShopPanel.transform);
            sellItemUi.transform.localScale = new Vector3(1,1,1);
            m_SellItem.Add(sellItemCom);
            m_WeaponFilterPanel.CheckFilter(sellItemCom);
        }

        for(int i=0; i<Player.Instance.GetNumShips(); ++i)
        {
            var sellShipUi = Instantiate(m_SellShipItemPerfab);
            if (!sellShipUi)
                continue;
            Ship ship = Player.Instance.GetShip(i);
            var sellShipCom = sellShipUi.GetComponent<SellShipItem>();
            if (sellShipCom)
            {
                sellShipCom.Ship = ship;
                sellShipCom.m_DescriptionPanel = m_ShipDescriptionPanel;
            }
            sellShipUi.transform.SetParent(m_ShipShopPanel.transform);
            sellShipUi.transform.localScale = new Vector3(1, 1, 1);
            m_SellShips.Add(sellShipCom);
        }
    }

    void CleanShopItem()
    {
        for(int i=0; i< m_WeaponShopPanel.transform.childCount; ++i)
        {
            var child = m_WeaponShopPanel.transform.GetChild(i);
            child.gameObject.SetActive(false);
        }
        for (int i = 0; i < m_ShipShopPanel.transform.childCount; ++i)
        {
            var child = m_ShipShopPanel.transform.GetChild(i);
            child.gameObject.SetActive(false);
        }
        for (int i = 0; i < m_WaterBoxShopPanel.transform.childCount; ++i)
        {
            var child = m_WaterBoxShopPanel.transform.GetChild(i);
            child.gameObject.SetActive(false);
        }
        foreach(var item in m_SellItem)
        {
            if(item)
                Destroy(item.gameObject);
        }
        m_SellItem.Clear();
        foreach(var item in m_SellShips)
        {
            if(item)
                Destroy(item.gameObject);
        }
        m_SellShips.Clear();
    }

    bool isSell = false;
    public void OnSellClicked(bool value)
    {
        isSell = value;
        Refresh();
    }
    public void Refresh()
    {
        CleanShopItem();
        Image image = GetComponent<Image>();
        if (isSell)
        {
            InitSellShopList();
            image.color = new Vector4(0.8f, 0.8f, 0.4f, 0.8f);
        }
        else
        {
            initShopList();
            image.color = new Vector4(1, 1, 1, 0.8f);
        }
    }

    /// <summary>
    /// 用户点击出售物品或者舰船的时候
    /// </summary>
    public void OnItemSellClicked()
    {
        if (m_SellSound)
        {
            m_SellSound.time = 0.04f;
            m_SellSound.Play();

        }
    }
    public void OnItemBuyClicked()
    {
        if (m_BuySound)
            m_BuySound.Play();
    }


}
